package com.zhuang.controller;

import com.zhuang.dto.AccessTokenDTO;
import com.zhuang.dto.GitHubUser;
import com.zhuang.mapper.UserMapper;
import com.zhuang.pojo.User;
import com.zhuang.pojo.UserExample;
import com.zhuang.provider.GitHubProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

@Controller
public class AuthorizeController {

    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${gitbut.uri}")
    private String uri;

    @Autowired
    private GitHubProvider gitHubProvider;
    @Resource
    private UserMapper userMapper;
    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state", required = false) String state,
                           HttpSession session,
                           HttpServletResponse response) {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(uri);
        String accessToken = gitHubProvider.getAccessToken(accessTokenDTO);
        GitHubUser gitHubUser = gitHubProvider.getUser(accessToken);
        if (gitHubUser != null) {
            User user = new User();
            user.setToken(UUID.randomUUID().toString());
            user.setName(gitHubUser.getName());
            user.setAccountId(Integer.parseInt(gitHubUser.getId()));
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            user.setAvatarUrl(gitHubUser.getAvatar_url());
            UserExample example = new UserExample();
            example.createCriteria().andAccountIdEqualTo(user.getAccountId());
            List<User> users = userMapper.selectByExample(example);
            if (users.size() == 0) {
                userMapper.insert(users.get(0));
            } else {
                user.setToken(users.get(0).getToken());
            }
            Cookie cookie = new Cookie("token", user.getToken());
            response.addCookie(cookie);
            session.setAttribute("user", user);
            return "redirect:/";
        } else {
            return "redirect:/";
        }
    }

}
